package com.example.onlineeducation.base

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.viewbinding.ViewBinding
import com.example.onlineeducation.databinding.WebCommonLayoutBinding


/**
 * SimpleDes:
 * Creator: Sindi
 * Date: 2022-01-05
 * UseDes:
 */
@SuppressLint("SetJavaScriptEnabled")
abstract class BaseWebActivity<VB : ViewBinding>(createVB: ((LayoutInflater) -> VB)? = null) : BaseActivity<VB>(createVB) {

    protected open var mUrl = ""
    protected open var mTitle: String? = ""


    protected fun WebCommonLayoutBinding.initWebviewSetting(titleCallBack: (() -> Unit)? = null) {
        val settings = webView.settings //WebView配置管理
        settings.javaScriptEnabled = true //支持JS
        settings.setSupportZoom(true) //设置可以支持缩放
        settings.builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.displayZoomControls = false //隐藏原生的缩放控件
        // settings.useWideViewPort = true //设置webview推荐使用的窗口，使html界面自适应屏幕(将图片调整到适合webview的大小)
        settings.loadWithOverviewMode = true //缩放至屏幕的大小，使用预览模式加载界面。
        settings.defaultFontSize = 16 //设置WebView默认字体最小值，默认值8，取值1到72
        // settings.textZoom = 100 //webview中加载页面字体变焦百分比，默认100，整型数。
        settings.loadsImagesAutomatically = true //支持自动加载图片
        settings.domStorageEnabled = true //设置DOM Storage缓存 ,https页面加载不出来就用它;
        settings.allowFileAccess = true //允许访问文件

        webView.apply {
            requestFocusFromTouch() //支持手势缩放（如webView中需要手动输入用户名、密码等，则webview必须设置支持获取手势焦点）
            webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(view: WebView, newProgress: Int) {
                    super.onProgressChanged(view, newProgress)
                    if (newProgress == 100) {
                        progressBar.visibility = View.GONE
                    } else {
                        progressBar.visibility = View.VISIBLE
                        progressBar.progress = newProgress //设置进度值
                    }
                }

                override fun onReceivedTitle(view: WebView?, title: String?) {
                    super.onReceivedTitle(view, title)
                    mTitle = title
                    titleCallBack?.invoke()
                }
            }
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    return false
                }
            }
        }
    }
}